package midderware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io"
)

type Logmidwarebuild struct {
	Logger *zap.Logger
	Input  bool
}

func NewlogBuild(logger *zap.Logger) *Logmidwarebuild {
	return &Logmidwarebuild{
		Logger: logger,
	}
}
func (l *Logmidwarebuild) LoggmidwareInput() *Logmidwarebuild {
	l.Input = true
	return l
}

func (l *Logmidwarebuild) Build() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		url := ctx.Request.URL.String()
		if len(url) > 2048 {
			url = url[:2048]
		}
		al := acceslog{
			Method: ctx.Request.Method,
			Url:    ctx.Request.RequestURI,
		}
		if l.Input {
			input, _ := io.ReadAll(ctx.Request.Body)                //流
			ctx.Request.Body = io.NopCloser(bytes.NewBuffer(input)) //使得能够读第二次
			al.Input = string(input)

		}
		defer func() {
			al.Machrout = ctx.FullPath()
			l.Logger.Debug("收到请求", zap.Any("req", al))
		}()
		ctx.Next()
	}
}

type acceslog struct {
	Method   string
	Url      string
	Input    string
	Machrout string
}
